#include "GraphEngine.h"


using namespace std;

GraphEngine::GraphEngine(void)
{
	this->camera.h=GraphEngine::screenH;
	this->camera.w=GraphEngine::screenW;
	this->camera.x=0;
	this->camera.y=0;
	this->screenSW=NULL;
};
void GraphEngine::init()
{
	screenSW=SDL_SetVideoMode(GraphEngine::screenW,GraphEngine::screenH,32,SDL_HWSURFACE);
	if (screenSW == NULL) 
	{
		fprintf(stderr, "Nie udalo sie ustawic trybu wideo: %s\n", SDL_GetError());
		exit(1);
	};
	SDL_Surface** tileSet;
	tileSet=new SDL_Surface*[g.tiles];
	for(unsigned int i=0;i<g.tiles;i++)
	{
		//tileSet[i]=SDL_LoadBMP(itoa(i)+".bmp");
	};

}
void GraphEngine::apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL )
{
    SDL_Rect offset;
    offset.x = x;
    offset.y = y;
    SDL_BlitSurface( source, clip, destination, &offset );
}
void GraphEngine::setCamera()
{
	this->camera.x=this->mapWidth;
	this->camera.y=this->mapHeight;
};
void GraphEngine::setGameEngine(GameEngine g)
{
	this->g=g;
	this->mapWidth=g.x*32;
	this->mapHeight=g.y*32;
};

void GraphEngine::setFollowedPlayer(int number=-1) //podajemy numer gracza lub jesli nie podamy zostanie ustawiony ten z "nasz wg tablicy z game engine"
{
	if(number==-1)
	{
		for(unsigned int i=0; i<g.x*g.y; i++)
		{
			if(g.getOwnPlayerState(i)==true)
			{
				this->followedPlayer=i;
			}
		}
	}
}
bool GraphEngine::check_collision( SDL_Rect A, SDL_Rect B )
{
    int leftA, leftB;
    int rightA, rightB;
    int topA, topB;
    int bottomA, bottomB;

    leftA = A.x;
    rightA = A.x + A.w;
    topA = A.y;
    bottomA = A.y + A.h;

    leftB = B.x;
    rightB = B.x + B.w;
    topB = B.y;
    bottomB = B.y + B.h;
    if( bottomA <= topB )
    {
        return false;
    }

    if( topA >= bottomB )
    {
        return false;
    }

    if( rightA <= leftB )
    {
        return false;
    }

    if( leftA >= rightB )
    {
        return false;
    }
    return true;
}
void GraphEngine::redrawMap(void)
{
	unsigned int mapWidth, mapHeight;
	mapWidth=g.x*32;
	mapHeight=g.y*32;
	SDL_Rect* clip=NULL;
	SDL_Rect currentTile={0,0,32,32};
	for(unsigned int i=0;i<g.x;i++)
		for(unsigned int j=0;j<g.y;j++)
		{
			currentTile.x=i*32+1;
			currentTile.y=j*32+1;
			if(check_collision(currentTile,camera))
			{
				apply_surface(currentTile.x,currentTile.y,g.getFromMapXY(i,j).picture,screenSW,clip);
			};
		}
}
SDL_Surface GraphEngine::LoadImage(char* filename)
{
	return *SDL_LoadBMP(filename);
};
void GraphEngine::wait(int time_ms)
{
    SDL_Delay(time_ms);
}	
GraphEngine::~GraphEngine(void)
{
	SDL_FreeSurface(screenSW);
}

void GraphEngine::refreshScreen(void)
{
	this->setCamera();
	this->redrawMap();
	SDL_Flip(screenSW);
};